package com.backend.demo1.controller;

import com.backend.demo1.config.ApiResponse;
import com.backend.demo1.models.Department;
import com.backend.demo1.services.DepartmentService;
import com.backend.demo1.models.User;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/departments")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @GetMapping
    public ResponseEntity<ApiResponse<List<Department>>> getAllDepartments() {
        List<Department> departments = departmentService.getAllDepartments();
        return ResponseEntity.ok().body(ApiResponse.success(departments));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Department>> getDepartmentById(@PathVariable Long id) {
        Department department = departmentService.getDepartmentById(id);
        return ResponseEntity.ok().body(ApiResponse.success(department));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Department>> createDepartment(@RequestBody Department department) {
        // 清除传入的 id，确保是新增操作
        department.setId(null);
        
        // 调用 service 层保存部门
        departmentService.saveDepartment(department);
        
        // 返回创建成功的响应，包含新创建的部门对象
        return ResponseEntity.ok().body(ApiResponse.success("部门创建成功",department));
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<String>> updateDepartment(
            @PathVariable Long id,
            @RequestBody Department department) {

        // 设置路径中的 id 到请求体对象中
        department.setId(id);

        // 调用 service 更新整个部门对象
        departmentService.updateDepartment(department);
        return ResponseEntity.ok().body(ApiResponse.success("部门信息更新成功", null));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<String>> deleteDepartment(@PathVariable Long id) {
        departmentService.deleteDepartment(id);
        return ResponseEntity.ok().body(ApiResponse.success("部门信息删除成功", null));
    }

    @GetMapping("/{id}/users")
    public ResponseEntity<ApiResponse<List<User>>> getUsersByDepartmentId(@PathVariable Long id) {
        List<User> users = departmentService.getUsersByDepartmentId(id);
        return ResponseEntity.ok().body(ApiResponse.success(users));
    }
}